package comman.duke.loader 
{
	import comman.duke.FloatHint;
	import comman.duke.GameUtils;
	import comman.duke.PoolMgr;
	import flash.events.*;
	import flash.net.*;
	import flash.external.ExternalInterface;
	/**
	 * ...
	 * @author jerry.d
	 */
	public class SomeUrlLoader 
	{
		public static const BAD_STATUS:Array = [404,500,302];
		private var loader:URLLoader;
		private var callBack:Function;
		private var errorBack:Function;
		public var proto:*;
		public static var NUM:uint = 0;
		public var name:String;
		public var tableId:int;
		
		public var request:URLRequest;
		
		public static const MAX_RESEND_TIMES:uint = 5;
		private var resendTimes:uint = 0;
		public function SomeUrlLoader() 
		{
			loader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.TEXT;
			loader.addEventListener(Event.COMPLETE, onComplete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHttpStatus);
			name = 'loader' + NUM;
			NUM++;
		}
		
		public function onHttpStatus(evt:HTTPStatusEvent):void{
			var status:int = evt.status;
			if ( status != 200){
				FloatHint.Instance.show("网络异常，错误码："+status);
				GameUtils.fatal('Http Status Error:' + status);
			}
		}

		public function load(proto:*, tabId:int, request:URLRequest, successHandler:Function, errorHandler:Function):void{
			this.proto = proto;
			loader.load(request);
			callBack = successHandler;
			this.tableId = tabId;
			errorBack = errorHandler;
			this.request = request;
		}
		
		public function resend():void{
			if ( this.request == null ){
				GameUtils.log('no request of the loader can\'t resend..');
			}else{
				resendTimes++;
				if( resendTimes <= MAX_RESEND_TIMES ){
					loader.load(this.request);
				}else{
					if( ExternalInterface.available )
						ExternalInterface.call("document.location.reload", true);
				}
			}
		}
		
		private function onComplete(e:Event):void{
			callBack(proto, tableId, loader.data, this);
		}
		
		private function onError(e:IOErrorEvent):void{
			errorBack(proto, tableId, e);
			reset();
			PoolMgr.reclaim(this);
		}
		
		public function reset():void{
			resendTimes = 0;
			this.request = null;
		}
	}
}